const Token = require('../../utils/token');
const utility = require('utility');
class User {
    /**
     * 登录
     * @api {POST}        /admin/login            登录
     * @apiName           /admin/login
     * @apiGroup          Administrator
     * @apiVersion 0.1.0
     * @apiParam          {String}            username    用户名
     * @apiParam          {String}            password    密码
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "登录成功",
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpJ9"
      }
     */
    async login(ctx) {
        let {
            db,
            request: {
                body: { username, password }
            }
        } = ctx;

        if (!username) {
            ctx.errors('用户名不能为空');
            return;
        }

        if (!password) {
            ctx.errors('密码不能为空');
            return;
        }

        let condition = {
            where: {
                username: username,
                password: utility.md5(password)
            },
            attributes: [
                'id',
                'username',
                'avatar',
                'role_id',
                'contract',
                'status'
            ],
            include: {
                as: 'role',
                attributes: ['id', 'role', 'remake'],
                required: true,
                model: db.Roles
            }
        };

        let data = await db.Admin.findOne(condition);

        if (!data) {
            // 如果没查找到,就尝试用手机号去查询
            condition.where.phone = username;
            delete condition.where.username;
            data = await db.Admin.findOne(condition);
            if (!data) {
                ctx.errors('用户名或密码错误');
                return;
            } else {
                if (!data.status) {
                    ctx.errors('账户已被禁用');
                    return;
                }
            }
        } else {
            if (!data.status) {
                ctx.errors('账户已被禁用');
                return;
            }
        }

        const {
            role: { id }
        } = data;

        const localToken = Token.createToken(data, id, '2', 'hours', 'admin');
        ctx.body = { code: 0, msg: '登录成功', token: localToken };
    }
    /**
     * 获取用户信息
     * @api {GET}         /admin/getMenu                     获取用户信息
     * @apiName           /admin/getMenu
     * @apiGroup          Administrator
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "",
        "avatar": "https://img.52z.com/upload/news/image/20171106/20171106094122_15964.jpg",
        "introduction": "欢迎！",
        "name": "超级管理员",
        "roles": [
            "admin"
        ]
       }
     */
    async Info(ctx) {
        let { db, user } = ctx;

        let condition = {
            attributes: ['username', 'avatar', 'role_id'],
            include: {
                as: 'role',
                where: {
                    id: user.User.role_id
                },
                attributes: ['id', 'role', 'remake', 'menu'],
                required: true,
                model: db.Roles
            }
        };

        let data = await db.Admin.findOne(condition);

        ctx.body = {
            code: 0,
            msg: '',
            avatar: data.avatar,
            introduction: '欢迎！',
            name: data.username,
            roles: [data.role.role]
        };
    }
    /**
     * 退出
     * @api {GET}        /admin/logout         退出
     * @apiName          /admin/logout
     * @apiGroup         Administrator
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "退出成功",
        "data": []
     }
     */
    async logout(ctx) {
        ctx.success();
    }
    /**
     * @api {PUT}        /admin/changePassword           更改当前管理员密码
     * @apiName          /admin/changePassword
     * @apiGroup         Administrator
     * @apiParam         {String}            oldPassword         原密码
     * @apiParam         {String}            newPassword         新密码
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "操作成功",
        "data": []
       }
     */
    async changePassword(ctx) {
        const {
            db,
            request: {
                body: { newPassword, oldPassword }
            },
            user
        } = ctx;

        if (!newPassword || !oldPassword) {
            ctx.errors('缺少参数');
            return;
        }

        let data = await db.Admin.findOne({
            where: { id: user.User.id, password: utility.md5(oldPassword) }
        });

        if (!data) {
            ctx.errors('修改失败');
            return;
        }

        data.password = utility.md5(newPassword);
        data.save();
        ctx.success();
    }
}
module.exports = new User();
